package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.feign.BehaviorFeign;
import com.usian.article.mapper.CollectionMapper;
import com.usian.article.service.CollectionService;
import com.usian.model.article.dtos.CollectionBehaviorDto;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

//收藏与取消收藏
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, ApCollection> implements CollectionService {
    @Autowired
    private BehaviorFeign apBehaviorFeign;

    //收藏与取消收藏
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        if (dto.getEntryId() == null || dto.getType() == null || dto.getOperation() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);}
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorFeign.findByUserIdOrEquipmentId(user.getId(), 0);
        if (apBehaviorEntry == null) {
            apBehaviorEntry = new ApBehaviorEntry();
            apBehaviorEntry.setCreatedTime(new Date());
            apBehaviorEntry.setEntryId(user.getId());
            apBehaviorEntry.setType((short) 1);
        }
        //查询是否收藏
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, dto.getEntryId()).eq(ApCollection::getEntryId, apBehaviorEntry.getId()));
        if (apCollection == null && dto.getOperation() == 0) {
            apCollection = new ApCollection();
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setCollectionTime(new Date());
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setType((short) 0);
            apCollection.setPublishedTime(new Date());
            save(apCollection);
            return ResponseResult.okResult("收藏成功");
        }else {
            if (dto.getOperation()==0){
                return ResponseResult.okResult("已收藏");
            }else{
                removeById(apCollection);
                return ResponseResult.okResult("已取消收藏");
            }
        }

    }
}
